import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class LifeCyclePage extends Component {
    static defaultProps = {
        msg:'omg'
    }
    static propTypes = {
        msg:PropTypes.string //.isRequired
    }
    constructor(props) {
        super(props);
        this.state = { count:0 }
        console.log("constructor")
    }
    //16.4之后生命周期
    static getDerivedStateFromProps(props, state){
        console.log("getDerivedStateFromProps")
        const {count} = state
        return count > 5 ? {count:0}:null
    }
    getSnapshotBeforeUpdate(prevProps, prevState){
        console.log("getSnapshotBeforeUpdate",prevProps, prevState)
        // return null
        return {
            msg:'2222'
        }
    }
    componentDidUpdate(prevProps, prevState,snapshot){
        const { count } = prevState;
        console.log("componentDidUpdate",snapshot)
    }
    // 16.4之前生命周期
    // componentWillMount(){
    //     console.log("componentWillMount")
    // }
    // componentDidMount(){
    //     console.log("componentDidMount")
    // }
    // shouldComponentUpdate(nextProps,nextState){
    //     const {count} = nextState
    //     console.log("shouldComponentUpdate",nextState,this.state.count)
    //     return count != 3 
    // }
    // componentWillUpdate(){
    //     console.log("componentWillUpdate")
    // }
    // componentDidUpdate(){
    //     console.log("componentDidUpdate")
    // }
    setCount=()=>{
        this.setState({
            count:this.state.count + 1
        })
    }
    render() { 
        console.log("render",this.props)
        const {count} = this.state
        return ( 
            <div>
                <h3>LifeCyclePage</h3>
                <p>{count}</p>
                <button onClick={this.setCount}>改变conut</button>
                {/* {count % 2 && <Child count={count}></Child>} */}
                <Child count={count}></Child>
            </div>
         );
    }
}

class Child extends Component {
    //16.4之前生命周期
    //初次渲染的识货不会执行，只有在已挂载的组件接受新的props的时候，才会执行
    // componentWillReceiveProps(nextProps){
    //     console.log("componentWillReceiveProps",nextProps)
    // }
    // componentWillUnmount(){
    //     console.log("componentWillUnmount")
    // }
    //npx react-codemod rename-unsafe-lifecycles,兼容16.4之后
    render() {
        console.log("Child render")
        const {count} = this.props;
        return ( 
            <div>
                <h3>Child</h3>
                <p>{count}</p>
            </div>
         );
    }
}
